package org.hagopa.games.moneypool.dblayer;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.hagopa.games.moneypool.dblayer.Connector.DBConnector;

public class PlayersInGameAdopt implements IDataAdopt {
	
	private long game_id = 0;
	private HashMap<Long, String> players = new HashMap<Long, String>();
	
	private String dbquery = "";
	
	public PlayersInGameAdopt(DBConnector dbcref, long gId) {
		
		this.game_id = gId;
		this.dbquery = "{call mp_get_gathered_players_list(?)};";
	}
	public boolean requestDB()
	{
		ResultSet rs = null;
        //Statement stmt = null;
        try {
       	 
			CallableStatement cs = DBConnector.getConn().prepareCall(this.dbquery);
       	    				//TODO: Should implement passing parameters to stored procedure
       	    cs.setLong(1, this.game_id);
       	    rs = cs.executeQuery();

       	    this.parseDBresponse(rs);
       	    rs.close();
       	    //stmt.close();
      	    		
       	} catch (SQLException e) {
      	    			// TODO Auto-generated catch block
        		e.printStackTrace();
        		return false;
      	}
        return true;
	}
	public void printAll(){
		Set  <Long> keys = players.keySet();
		Iterator <Long> itr = keys.iterator();
		while(itr.hasNext())
		{
			Long skey = (Long)itr.next();
			String name = (String)players.get(skey);
			itr.remove();
			System.out.println("Id: " + skey + ", Name: "+ name);
		}
		
	}
	public String getQuery() {
		// TODO Auto-generated method stub
		
		return this.dbquery;
	}

	public boolean parseDBresponse(ResultSet rs) {
		// TODO Auto-generated method stub
		try {
			while(rs.next())
			{
				this.players.put(new Long(rs.getInt("user_id")), rs.getString("user_name"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public String getQueryType() {
		// TODO Auto-generated method stub
		return "proc";
	}

}
